package com.authorization.storage;

import com.authentication.LoginSuccessAuthentication;
import com.authentication.RBACUser;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


public class InMemoryAuthorityStorageManager implements AuthorityStorageManager<GrantedAuthority>{

    private final Map<Long,Collection<GrantedAuthority>> map = new ConcurrentHashMap<>();

    @Override
    public void storage(Authentication authentication) {

        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();


        if(!authentication.isAuthenticated()|| CollectionUtils.isEmpty(authorities)){
            return;
        }

        RBACUser principal = (RBACUser) authentication.getPrincipal();

        @SuppressWarnings("unchecked")
        Collection<GrantedAuthority> authorities1 = (Collection<GrantedAuthority>) authorities;

        map.put(principal.getUserId(), authorities1);
    }

    @Override
    public Collection<GrantedAuthority> load(Authentication authentication) {
        if(!authentication.isAuthenticated()){
            return Collections.emptyList();
        }
        RBACUser rbacUser = (RBACUser) authentication.getPrincipal();
        Collection<GrantedAuthority> result = map.get(rbacUser.getUserId());
        if(CollectionUtils.isEmpty(result)){
            return Collections.emptyList();
        }
        return result;
    }
}
